<script setup lang="ts">
  import { MODE } from '@/components/CodeEditor';
  import { decodeApi } from '@/api/hc/iotCoder';
  import { ref, watch } from 'vue';
  import { IotUniDataLog } from '@/api/hc/iotDeviceData';
  import CodeEditor from '@/components/CodeEditor/src/CodeEditor.vue';

  const rawWrapper = ref('');
  const contents = ref('');
  const json = ref('');
  const resValue = ref('');

  // eslint-disable-next-line vue/valid-define-props
  const props = defineProps<{
    iotUniDataLog: IotUniDataLog | undefined;
  }>();

  watch(props, () => {
    a();
  });

  function base64ToUint8Array(base64String: string): Uint8Array {
    const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
    const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
    const rawData = window.atob(base64);
    const outputArray = new Uint8Array(rawData.length);

    for (let i = 0; i < rawData.length; ++i) {
      outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
  }

  function a() {
    if (!props.iotUniDataLog) {
      return;
    }
    rawWrapper.value = JSON.stringify(props.iotUniDataLog);
    contents.value = props.iotUniDataLog.contents;
    if (props.iotUniDataLog.action.startsWith('up:set')) {
      decodeApi(props.iotUniDataLog).then((res) => {
        resValue.value = res;
      });
    } else {
      console.error('unKnow action', props.iotUniDataLog.action);
    }

    try {
      const uint8Array = base64ToUint8Array(contents.value);
      json.value = String.fromCharCode.apply(String, uint8Array);
    } catch (e) {
      console.error(e);
    }
  }
</script>

<template>
  <div>
    <div>raw</div>
    <CodeEditor v-model:value="rawWrapper" :mode="MODE.JSON" />
    <div>content</div>
    <CodeEditor v-model:value="contents" :mode="MODE.JSON" />
    <div>json</div>
    <CodeEditor v-model:value="json" :mode="MODE.JSON" />
    <div>decode</div>
    <CodeEditor v-model:value="resValue" :mode="MODE.JSON" />
  </div>
</template>

<style scoped lang="less"></style>
